﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using IrisMembership.DataLayer;
using IrisMembership.ServiceLayer;
using Newtonsoft.Json;
using IrisMembership.DomainClasses;

namespace IrisMembership.Web.Controllers
{
    [RoutePrefix("user")]
    public class UserController : Controller
    {
        private readonly IIrisDbContext _dbContext;
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;

        public UserController(IIrisDbContext dbContext, IUserService userService, IRoleService roleService)
        {
            _dbContext = dbContext;
            _userService = userService;
            _roleService = roleService;
        }

        public ActionResult Index()
        {
            return PartialView();
        }
        public ActionResult AuthorizedRolesList()
        {
            return PartialView();
        }

        public ActionResult UsersList()
        {
            return PartialView();
        }

        [Route("userslist/{roleId:int}")]
        public async Task<ActionResult> UsersList(int roleId)
        {
            var users = await _userService.GetUsersListByRoleIdAsync(roleId);

            var data =
                await
                    JsonConvert.SerializeObjectAsync(users, Formatting.Indented,
                        new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
            return
                Content(data);
        }

        public ActionResult ManageUserRoles()
        {
            return PartialView();
        }

        [HttpPost]
        public async Task<ActionResult> ChangeUserRoles(int userId, ICollection<int> rolesId)
        {
            var selectedUser = await _userService.FindByUserIdAsync(userId);

            if (selectedUser.Roles != null && selectedUser.Roles.Any())
                selectedUser.Roles.Clear();

            if (rolesId != null)
            {
                foreach (var roleId in rolesId)
                {
                    selectedUser.Roles.Add(_roleService.Find(roleId));
                }
            }
            else
            {
                selectedUser.Roles.Add(_roleService.Find(2));
            }

            await _dbContext.SaveChangesAsync();

            return Json("ok");
        }

    }
}